<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\middleware\Auth;
use app\model\ProductSalesSpecsModel;
use app\model\ProductsModel;
use app\model\ShopsModel;
use app\model\UserModel;
use app\model\UserShopCarModel;
use think\App;
use think\facade\Db;

class UserShopCar extends Base {

    protected $middleware = [Auth::class];

    private $userShopCarModel;

    private $productsModel;

    private $shopsModel;

    private $specSalesModel;

    private $req;

    private $uid;



    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->userModel = new UserModel();

        $this->userShopCarModel = new UserShopCarModel();

        $this->productsModel = new ProductsModel();

        $this->shopsModel = new ShopsModel();

        $this->specSalesModel = new ProductSalesSpecsModel();

        $this->req = request()->param();

        $this->header = request()->header();

        $this->uid = $this->isLogin();

    }

    /*
     *  添加商品到购物车
     * */
    public function addProductUserShopCar()
    {

        $specsList = $this->req["specs"];

        if(empty($specsList)){
            return $this->fail("参数错误:specs 不能为空");
        }

        $data=[];
        foreach ($specsList as  $spec){
            if(empty($spec['spec_id'])){
                return $this->fail("参数错误:spec_id 不能为空");
            }

            if($spec['num'] < 1){
                return $this->fail("参数错误:商品数量不合法");
            }

            //检查规格
            $specInfo = $this->specSalesModel->getInfo($spec['spec_id']);

            if($specInfo["buy_status"] != 1){
                return $this->fail($specInfo["spec_name"].$specInfo["buy_status_msg"]);
            }

            if($specInfo['stock'] - $specInfo['sales_num'] < $spec['num']){
                return $this->fail($specInfo["spec_name"]."该规格商品库存不足");
            }

            $save=[];
            $save['shop_id'] = $specInfo['shop_id'];
            $save['product_id'] = $specInfo['product_id'];
            $save['spec_id'] = $specInfo['spec_id'];
            $save['num'] = $spec['num'];
            $data[] = $save;
        }

        //添加商品到购物车
        foreach ($data as $one){
            $where=[];
            $where['uid'] = $this->uid;
            $where['product_id'] = $one["product_id"];
            $where['spec_id'] = $one["spec_id"];
            if($this->userShopCarModel->getTotal($where)){
                $res = $this->userShopCarModel->where([
                    "uid"=>$this->uid,
                    "spec_id"=>$one["spec_id"],
                ])->inc("num",$one["num"])->update();
            }else{
                $res = $this->userShopCarModel->addOne([
                    "uid"=>$this->uid,
                    "shop_id"=> $one["shop_id"],
                    "product_id"=>$one["product_id"],
                    "spec_id"=>$one["spec_id"],
                    "num"=>$one["num"],
                ]);
            }
        }

        if($res){
            return $this->succ([],"添加成功");
        }else{
            return $this->fail("添加失败");
        }
    }




    /*
  * 获取购物车商品数量
  *
  * */
    public function getUserShopCarProductsNum()
    {
        $where=[];
        $where[] = ["uid",'=',$this->uid];
        $where[] = ["shop_car_status",'=',1];
        $total = $this->userShopCarModel->getTotal($where);
        return $this->succ($total);
    }


    /*
     * 获取购物车商品列表
     *
     * */
    public function getUserShopCarProductsList()
    {
        $where=[];
        $where[] = ["uid",'=',$this->uid];
        $where[] = ["shop_car_status",'=',1];

        $total = $this->userShopCarModel->getTotal($where);
        $return =[];
        if($total > 0){
            $data = $this->userShopCarModel->getList($where);

            if($data){
                foreach ($data as $val){
                    $shop_id = $val['shop_id'];
                    if(!isset($return[$shop_id])){
                        $return[$shop_id] = $this->shopsModel->getInfo($shop_id);
                    }

                    $productInfo = $this->productsModel->getBaseInfo($val["product_id"]);

                    $specInfo = $this->specSalesModel->getInfo($val["spec_id"]);

                    $specInfo["producet_spec_list"] = $this->specSalesModel->getProductSalesSpecsList($val["product_id"]);
                    
                    $return[$shop_id]['product_list'][] = array_merge($productInfo,$specInfo,$val);
                }

                $return = array_values($return);
            }
        }

        return $this->succData($total,$return);
    }




    /*
    * 切换规格
    *
    * */
    public function changeUserShopProductNum(){


        if(empty($this->req['shop_car_id'])){
            return $this->fail("参数错误：请选择规格");
        }


        if(empty($this->req['spec_id'])){
            return $this->fail("参数错误：请选择规格");
        }


        if(empty($this->req['num']) || $this->req['num'] < 1){
            return $this->fail("参数错误：数量不能为0");
        }

        //检查规格
        $specInfo = $this->specSalesModel->getInfo($this->req['spec_id']);

        if($specInfo["buy_status"] != 1){
            return $this->fail($specInfo["spec_name"].$specInfo["buy_status_msg"]);
        }

        $isExist = $this->userShopCarModel->getShopCarProductsNum($this->uid,$this->req['spec_id']);
        $num = $this->req['num'] + $isExist;
        if($specInfo['stock'] - $specInfo['sales_num'] < $num){
            return $this->fail("该规格商品库存不足");
        }


        //删除原来的购物车商品
        $delRes = $this->userShopCarModel->delAll([
            "shop_car_id"=>$this->req['shop_car_id']
        ]);

        if($isExist){
            //新增操作
            $addRes = $this->userShopCarModel->changeUserShopProductNum($this->uid,$this->req['spec_id'],$num);
        }else{
            //添加操作
            $addRes = $this->userShopCarModel->addOne([
                "uid"=>$this->uid,
                "shop_id"=> $specInfo['shop_id'],
                "product_id"=>$specInfo['product_id'],
                "spec_id"=>$this->req['spec_id'],
                "num"=>$num,
            ]);
        }

        if($addRes){
            return $this->succ();
        }

        return $this->fail();
    }


    /*
  * 增加商品指定规格商品的数量
  *
  * */
    public function incrUserShopProductNum(){

        if(empty($this->req['spec_id'])){
            return $this->fail("参数错误：请选择规格");
        }


        if(!isset($this->req['num']) ){
            return $this->fail("参数错误：num存在");
        }

        //删除操作
        if($this->req['num'] <=  0){
            $where =[];
            $where['shop_car_status'] = 1;
            $where['uid'] = $this->uid;
            $where['spec_id'] = $this->req["spec_id"];
            $this->userShopCarModel->delAll($where);
            return  $this->succ("商品被移除");
        }


        //检查规格
        $specInfo = $this->specSalesModel->getInfo($this->req['spec_id']);

        if($specInfo["buy_status"] != 1){
            return $this->fail($specInfo["spec_name"].$specInfo["buy_status_msg"]);
        }

        $isExist = $this->userShopCarModel->getShopCarProductsNum($this->uid,$this->req['spec_id']);

        if($specInfo['stock'] - $specInfo['sales_num'] < $this->req['num']){
            return $this->fail("该规格商品库存不足");
        }


        if($isExist){
            //新增操作
            $addRes = $this->userShopCarModel->changeUserShopProductNum($this->uid,$this->req['spec_id'],$this->req['num']);
        }else{
            //添加操作
            $addRes = $this->userShopCarModel->addOne([
                "uid"=>$this->uid,
                "shop_id"=> $specInfo['shop_id'],
                "product_id"=>$specInfo['product_id'],
                "spec_id"=>$this->req['spec_id'],
                "num"=>$this->req['num'],
            ]);
        }

        if($addRes){
            return $this->succ($this->req['num']);
        }

        return $this->fail();
    }




    /*
     * 减少商品指定规格商品的数量
     *
     * */
    public function decrUserShopProductNum(){

        if(!isset($this->req['num'])){
            return $this->fail("参数错误：num错误");
        }

        //删除操作
        if($this->req['num'] <= 0){
            $where =[];
            $where['shop_car_status'] = 1;
            $where['uid'] = $this->uid;
            $where['spec_id'] = $this->req["spec_id"];
            $this->userShopCarModel->delAll($where);
            return  $this->succ("商品被移除");
        }

        $addRes = $this->userShopCarModel->changeUserShopProductNum($this->uid,$this->req['spec_id'],$this->req['num']);

        if($addRes){
            return $this->succ();
        }else{
            return $this->fail();
        }
    }


    /*
   * 删除购物车指定商品
   *
   * */
    public function batchDelUserShopProduct(){
        if(empty($this->req['spec_ids'])){
            return $this->fail("参数错误：spec_ids为空");
        }

        $where =[];
        $where[] = ['shop_car_status',"=",1];
        $where[] = ['uid',"=",$this->uid];
        $where[] = ['spec_id',"in",$this->req['spec_ids']];

        $res = $this->userShopCarModel->delAll($where);

        if($res){
            return $this->succ();
        }

        return $this->fail();

    }


}
